const tbody = document.querySelector('tbody');
const addForm = document.querySelector('.add-form');
const updateForm = document.querySelector('.update-form');

// 获取学生数据生成
getStudentList()

// 初始化添加表单中的城市选项
initSelect('#addModal')

// 初始化编辑表单中的城市选项
initSelect('#updateModal')

// 增加学生信息功能
addForm.addEventListener('submit', function (e) {
    e.preventDefault()
    const data = $(this).serialize()
    axios.post('/student/add', data)
        .then(result => {
            if (result.data.code === 0) {
                toastr.success(result.data.message)
                addForm.reset()
                $('#addModal').modal('hide')
                getStudentList()
            }
        })
})

// 给tbody 添加点击事件
tbody.addEventListener('click', function (e) {
    const dom = e.target
    if (dom.classList.contains('updateBtn')) {
        $('#updateModal').modal('show')
        const id = dom.dataset.id
        axios.get('/student/one', { params: { id } })
            .then(result => {
                const obj = result.data.data
                for (const key in obj) {
                    const target = document.querySelector(`#updateModal [name=${key}]`);
                    // 表单 性别选项栏选中
                    if (key === 'sex') {
                        document.querySelector(`#updateModal [name=sex][value=${obj.sex}]`).checked = true
                        continue
                    }
                    // 普通表单内容填充
                    if (target) {
                        target.value = obj[key]
                    }
                }
                // 根据省份来生成对应市。并且选中对应信息
                renderSelect('/geo/city',
                    { pname: obj.province },
                    document.querySelector('#updateModal [name=city]'),
                    '市',
                    obj.city
                )
                // /根据省市来生成对应县。并且选中对应信息
                renderSelect('/geo/county',
                    { pname: obj.province, cname: obj.city },
                    document.querySelector('#updateModal [name=county]'),
                    '县',
                    obj.county,
                )
            })
    } else if (dom.classList.contains('deleteBtn')) {
        if (confirm('您确定要删除吗？')) {
            const id = dom.dataset.id
            axios.delete('/student/delete', { params: { id } })
                .then(result => {
                    if (result.data.code === 0) {
                        toastr.success(result.data.message)
                        getStudentList()
                    }
                })
        }
    }
})

// 编辑表单提交修改功能
updateForm.addEventListener('submit', function (e) {
    e.preventDefault()
    const data = $(this).serialize()
    axios.put('/student/update', data)
        .then(result => {
            toastr.success(result.data.message)
            updateForm.reset()
            getStudentList()
            $('#updateModal').modal('hide')
        })
})

// 获取学生数据并渲染函数
function getStudentList() {
    axios.get('/student/list')
        .then(result => {
            // console.log(result);
            if (result.data.code === 0) {
                let arr = result.data.data
                tbody.innerHTML = arr.reduce((h, v) => h + `
                <tr>
                    <th scope="row">${v.id}</th>
                    <td>${v.name}</td>
                    <td>${v.age}</td>
                    <td>${v.sex}</td>
                    <td>${v.group}</td>
                    <td>${v.phone}</td>
                    <td>${v.salary}</td>
                    <td>${v.truesalary}</td>
                    <td>${v.province + v.city + v.county}</td>
                    <td>
                      <button type="button" class="btn btn-primary btn-sm updateBtn" data-id=${v.id}>修改</button>
                      <button type="button" class="btn btn-danger btn-sm deleteBtn" data-id=${v.id}>删除</button>
                    </td>
                </tr>
                `, '')
            }
        })
}

// 渲染城市选项标签函数
function renderSelect(url, params, dom, label, value = '') {
    axios.get(url, { params })
        .then(result => {
            dom.innerHTML = result.data.reduce((h, v) => h + `
            <option value="${v}">${v}</option>
            `, `<option value="">--${label}--</option>`)
            dom.value = value
        })
}

// 初始化表单中城市选项内容
function initSelect(selector) {
    const provinceSelect = document.querySelector(`${selector} [name=province]`);
    const citySelect = document.querySelector(`${selector} [name=city]`);
    const countySelect = document.querySelector(`${selector} [name=county]`);
    // 添加学员模态框中省份信息选项获取数据
    renderSelect('/geo/province', {}, provinceSelect, '省')
    // 根据省份获取城市列表
    provinceSelect.addEventListener('change', function () {
        renderSelect('/geo/city', { pname: provinceSelect.value }, citySelect, '市')
    })
    // 根据省市的选择获取对应县的数据
    citySelect.addEventListener('change', function () {
        renderSelect('/geo/county',
            { pname: provinceSelect.value, cname: citySelect.value },
            countySelect,
            '县')
    })
}